import Vue from 'vue'
import VueRouter from 'vue-router'

import instance from '@/utils/request.js';

import { Message } from 'element-ui';

Vue.use(VueRouter)


// 引入口碑路由配置
import koubei from './koubei';

// 引入文章路由配置
import article from './article';

// 引入文章路由配置
import flink from './flink';

// 引入文章路由配置
import user from './user';

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    component: () => import('../views/Index.vue'),
    children: [
      {
        path: '', component: () => import('../views/home/Home.vue'),
      },
      ...koubei,
      ...article,
      ...flink,
      ...user
      
    ]
  },
  {
    path: '/register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/login',
    component: () => import('../views/Login.vue')
  },
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 路由守卫
// 路由实例对象router有一个beforeEach()方法，在进入路由之前做什么事
// 这个方法里面是一个回调函数，这个回调函数有三个参数：to, from ,next
// to 到哪里去；  from 从哪里来； next 通过

// 想要进入哪个路由，先经过路由守卫的同意
router.beforeEach(function (to, from, next) {
  if (to.path === '/login' || to.path === '/register') {
    // 同意通过
    next();
  } else {
    instance({
      method: 'post',
      url: '/admin/verifyToken'
    }).then(r => {
      // console.log(r.data);
      if (r.data.code === 0) {
        // 通过
        next();
      } else {
        Message.error('token有误')
        router.push('/login')
      }

    })
  }
})


export default router
